package com.demo.xhskd;

import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.eclipse.jetty.util.StringUtil;

import cn.ljl.sand.jws.OutSideDataReceiveItf;
import cn.ljl.sand.jws.OutSideDataReceiveItfPortType;

import com.demo.common.model.Khsx2;
import com.demo.common.model.Ncdzb;
import com.demo.common.model.Xhskd;
import com.demo.general.Khsx2Service;
import com.demo.general.NcdzbService;
import com.demo.ncfsjl.NCFSJLService;
import com.jfinal.aop.Inject;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.SqlPara;

/**
 * 本 demo 仅表达最为粗浅的 jfinal 用法，更为有价值的实用的企业级用法
 * 详见 JFinal 俱乐部: http://jfinal.com/club
 * 
 * JhfkdService
 * 所有 sql 与业务逻辑写在 Service 中，不要放在 Model 中，更不
 * 要放在 Controller 中，养成好习惯，有利于大型项目的开发与维护
 */
public class XhskdService {
	
	@Inject
	NCFSJLService fsjlservice;
	@Inject
	NcdzbService ncdzbService;
	@Inject
	Khsx2Service khsx2Service;
	
	/**
	 * 所有的 dao 对象也放在 Service 中，并且声明为 private，避免 sql 满天飞
	 * sql 只放在业务层，或者放在外部 sql 模板，用模板引擎管理：
	 * 			http://www.jfinal.com/doc/5-13
	 */
	private Xhskd dao = new Xhskd().dao();
	
//	private String startDate = null;
	
//	private String endDate = null;
	
	public Page<Xhskd> paginate(int pageNumber, int pageSize) {
		return dao.paginate(pageNumber, pageSize, "select *", "from XHSKD order by RQ desc");
	}
	
	public Page<Xhskd> paginate(int pageNumber, int pageSize,String startDate,String endDate) {

		StringBuilder sql = new StringBuilder();
		sql.append("from XHSKD WHERE 1=1");
		if(startDate != null && startDate.length()>1) {
			sql.append(" AND RQ>='"+startDate+"'");
		}
		if(endDate != null && endDate.length()>1) {
			sql.append(" AND RQ<='"+endDate+"'");
		}
		sql.append(" ORDER BY RQ DESC");
		return dao.paginate(pageNumber, pageSize, "select *", sql.toString());
	}

	public List<Xhskd> findList(String id) {
		StringBuilder sql = new StringBuilder();
		sql.append("from XHSKD WHERE 1=1");
//		if(startDate != null && startDate.length()>1) {
//			sql.append(" AND RQ>='"+startDate+"'");
//		}
//		if(endDate != null && endDate.length()>1) {
//			sql.append(" AND RQ<='"+endDate+"'");
//		}
		sql.append(" ORDER BY RQ DESC");
		SqlPara sqlPara = new SqlPara();
		return dao.find(sqlPara);
	}
	
	public Xhskd findById(String id) {
		return dao.findById(id);
	}
	
	public void deleteById(String id) {
		dao.deleteById(id);
	}
	
	public boolean isXml(String str) {
		boolean flag = true;
		try {
			DocumentHelper.parseText(str);
		} catch (Exception e) {
			flag = false;
		}
		return flag;
	}
	
	public Document makeXhskdXml(Xhskd xhskdBean) throws Exception {
		// List<Jhfkdmx> listMx = mxservice.find(jhfkdBean.getStr("DJBH"));

		Element root = DocumentHelper.createElement("DataBill");
		Document doucment = DocumentHelper.createDocument(root);

		root.addElement("MessageID").addText(xhskdBean.getStr("DJBH"));// 唯一标识，随机字符
		root.addElement("TargetSystem").addText("OMERP");
		root.addElement("billtype").addText("GATHERBILL");
		root.addElement("description").addText(xhskdBean.getStr("DJBH"));

		Element mainTable = root.addElement("maintable");
		mainTable.addElement("billid").addText("");// 单据id，由查询接口返回，新增时此节点值为空，修改时不能为空
		Khsx2 sx = khsx2Service.findByKHDM(xhskdBean.getStr("DM1"));
		String pk_org = StringUtil.isBlank(sx.getStr("BYZD1")) == true ? "01" : sx.getStr("BYZD1");
		mainTable.addElement("pk_org").addText(pk_org);// NC组织编码
		mainTable.addElement("billdate").addText(xhskdBean.getStr("RQ").substring(0, 10));// "2018-11-17"单据日期，注意格式
		mainTable.addElement("oldbillno").addText(xhskdBean.getStr("DJBH"));// 原单据号->对方系统单据号
		mainTable.addElement("scomment").addText("");// 摘要

		Element bodys = mainTable.addElement("bodys");
		Element item = bodys.addElement("item");

		item.addElement("itemid").addText(String.valueOf(1));// 明细行号
		item.addElement("src_billid").addText("");// 来源单据ID
		item.addElement("src_itemid").addText("");// 来源行号
		Ncdzb dzb = ncdzbService.findById(xhskdBean.getStr("DM1"));
		if (dzb == null) {
			throw new Exception("NC供货商编码为空");
		}
		item.addElement("custsup").addText(dzb.getStr("NCMD"));// NC供应商编码
		item.addElement("scomment").addText(xhskdBean.getStr("BZ"));// 摘要abc211（说明）
		item.addElement("subjcode").addText("112201");// 贷方科目编码
		item.addElement("pk_currtype").addText("CNY");// 默认CNY
		item.addElement("rate").addText("1");// 汇率，默认为1
		item.addElement("pk_deptid").addText("");// 部门编码
		item.addElement("money").addText(xhskdBean.getStr("SJJE"));// 借方原币金额
		item.addElement("contractno").addText("");// 合同号
		item.addElement("cashaccount").addText("");// 账号类型
		item.addElement("bankno").addText("");// 收款银行账号
		item.addElement("pk_balatype").addText("3");// 结算方式编码
		item.addElement("busidate").addText(xhskdBean.getStr("RQ").substring(0, 10));// 起算日期，长度8位
		String pp = xhskdBean.getStr("DM1").contains("T") == true ? "PP02" : "PP01";
		item.addElement("brands").addText(pp);// 品牌
		item.addElement("prepay").addText("1");// 预收款类型

		return doucment;
	}
	
	public void syncupdate(String djbh) throws Exception {
		Xhskd xhskdBean = dao.findById(djbh);
		Document doc = makeXhskdXml(xhskdBean);
		System.out.println(doc.asXML());
//		OutSideDataReceiveItf os = new OutSideDataReceiveItf();
//		OutSideDataReceiveItfPortType datRecv = os.getOutSideDataReceiveItfSOAP11PortHttp();
//		String str = datRecv.receiveXmlData(doc.asXML(), "GATHERBILL");
//		String result = "0", comment = "";
//		if (isXml(str)) {
//			try {
//				Document document = DocumentHelper.parseText(str);
//				Element ele0 = document.getRootElement();
//				Element ele1 = ele0.element("result");
//				result = ele1.getTextTrim();
//				Element ele2 = ele0.element("comment");
//				comment = ele2.getTextTrim();
//			} catch (DocumentException e) {
//				e.printStackTrace();
//			}
//		}
//		if (comment == "") {
//			comment = str;
//		}
//		fsjlservice.insertNCFSJL(xhskdBean.getStr("DJBH"), doc.asXML(), result, str, comment);
	}
}
